package controller

import (
	"ginEssential/common"
	"ginEssential/model"
	"ginEssential/response"
	"ginEssential/vo"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"strconv"
)

type IDepartmentController interface {
	RestController
}

type DepartmentController struct {
	DB *gorm.DB
}

func NewDepartmentController() DepartmentController {
	db := common.GetDB()
	db.AutoMigrate(model.Department{})
	return DepartmentController{DB: db}
}

func (d DepartmentController) Create(ctx *gin.Context) {
	var requestDepartment vo.CreateDepartmentRequest

	if err := ctx.ShouldBind(&requestDepartment); err != nil {
		response.Fail(ctx, "数据验证错误，部门名必填", nil)
		return
	}

	department := model.Department{DepartmentName: requestDepartment.DepartmentName}

	d.DB.Create(&department)
	response.Success(ctx, gin.H{"department": department}, "")
}

func (d DepartmentController) Update(ctx *gin.Context) {
	var requestDepartment vo.UpdateDepartmentRequest

	if err := ctx.ShouldBind(&requestDepartment); err != nil {
		response.Fail(ctx, "数据验证错误，部门名必填", nil)
		return
	}

	departmentId, _ := strconv.Atoi(ctx.Params.ByName("id"))

	var updateDepartment model.Department
	if d.DB.First(&updateDepartment, departmentId).RecordNotFound() {
		response.Fail(ctx, "部门不存在", nil)
		return
	}

	d.DB.Model(&updateDepartment).Update("department_name", requestDepartment.DepartmentName).
		Update("auto_name", requestDepartment.AuthName).Update("p_id", requestDepartment.PID).
		Update("path", requestDepartment.PATH)

	response.Success(ctx, gin.H{"department": updateDepartment}, "修改成功")
}

func (d DepartmentController) Show(ctx *gin.Context) {
	departmentId, _ := strconv.Atoi(ctx.Params.ByName("id"))

	var Department model.Department
	if d.DB.First(&Department, departmentId).RecordNotFound() {
		response.Fail(ctx, "部门不存在", nil)
		return
	}
	response.Success(ctx, gin.H{"department": Department}, "查询成功")
}

func (d DepartmentController) Delete(ctx *gin.Context) {
	departmentId, _ := strconv.Atoi(ctx.Params.ByName("id"))

	if err := d.DB.Delete(model.Department{}, departmentId).Error; err != nil {
		response.Fail(ctx, "删除失败，请重试", nil)
		return
	}
	response.Success(ctx, nil, "删除成功")
}
